
package br.unirio.bsi.mono.ForumSite.action;

import flexjson.JSONSerializer;

import org.apache.struts.action.*;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.unirio.bsi.mono.ForumSite.beans.loginForm;
import br.unirio.bsi.mono.ForumSite.model.dao.GenericDAO;

import br.unirio.bsi.mono.ForumSite.beans.formBeanC;
import br.unirio.bsi.mono.ForumSite.beans.formBeanCL;
import br.unirio.bsi.mono.ForumSite.beans.commentForm;
import java.sql.Date;
import java.sql.Timestamp;

public class commentAction extends Action 
{
  @Override
  public ActionForward execute(ActionMapping mapping, 
                               ActionForm form,
                               HttpServletRequest request, 
                               HttpServletResponse response) throws Exception 
  {      
    // pega a session
    HttpSession session = request.getSession();  
    
    // check logged
    loginForm lf = (loginForm)session.getAttribute("loginForm"); 
    if( lf == null || !lf.isLogged() )
      return null;
    
    // pega instancia do DAO    
    GenericDAO gD = GenericDAO.getInstance(getResources(request).getMessage("DB_NAME"));
    
    // copy
    commentForm cF = (commentForm)form;
    
    // parameter
    if( cF.getOperation() != null && 
        cF.getOperation().equals( commentForm.OPERATION_INSERT ) )
    {
      String selCom = cF.getSelectedComment();
      if( selCom != null && !selCom.isEmpty() )
      {      
        // alloca novo comment
        formBeanC comment = new formBeanC();  
        
        comment.setTitulo( cF.getTitulo() );
        comment.setMensagem( cF.getMensagem() );
        comment.setTipo( cF.getTipo() );
        comment.setNivel( Integer.valueOf( cF.getSelectedComment() ) );
        comment.setIDUsuario(lf.getId());
        comment.setData( new Timestamp( new java.util.Date().getTime() ) );
        
        // coloca no banco
        gD.insert( comment );
        
        // pega id do recem inserido
        gD.retrieve( comment );
        
        // insere o estado
        formBeanCL cml = new formBeanCL();
        
        cml.setIDComentario( comment.getID() );
        cml.setIDUsuario( comment.getIDUsuario() );
        cml.setLido(0);
        
        gD.insert( cml );
        
        cF.setSelectedComment("");
      }
    }
    else
    if( cF.getOperation() != null && 
        cF.getOperation().equals( commentForm.OPERATION_REMOVE ) )
    {
      // alloca novo comment
      formBeanC comment = new formBeanC();      
      comment.setID( Integer.parseInt( cF.getSelectedComment() ) );
      
      gD.retrieve( comment );
      
      // verifica se o comentario eh do usuario logado
      if( comment.getIDUsuario() == lf.getId() )
        // remove do banco
        gD.execute( "DELETE FROM Comentario WHERE ID=" + cF.getSelectedComment() );
      
      cF.setSelectedComment("");
    }

    
    // return listing
    String selPage = cF.getSelectedPage();
    String selCom = cF.getSelectedComment();
    
    if( selCom != null && !selCom.equals("") )
    {
      gD.retrieveAll( "SELECT DISTINCT c.*, u.nome as usuarioNome " +
                      "FROM Comentario c, Usuario u " +
                      "WHERE  c.id = " + selCom +                      
                      " ORDER BY c.id ASC " +                            
                      "OFFSET " + selPage +              
                      " LIMIT 35",       
                      formBeanC.class, cF.getComments() );  
      
      // usuaro crico pra ler
      formBeanCL cml = new formBeanCL();
        
      cml.setIDComentario( cF.getComments().get(0).getID() );
      cml.setIDUsuario( cF.getComments().get(0).getIDUsuario() );

      if( gD.retrieve( cml ) == null )
      {
        cF.getComments().get(0).setLido( 0 );
        
        cml.setLido(1);   
        
        gD.insert( cml );     
      }
      else
        cF.getComments().get(0).setLido( cml.getLido() );
      
    }   
    else
    {
      gD.retrieveAll( "SELECT DISTINCT c.*, u.nome as usuarioNome " +
                      "FROM Comentario c, Usuario u " +
                      "WHERE u.id = c.idusuario " +                 
                      " ORDER BY c.id ASC " +                            
                      "OFFSET " + selPage +              
                      " LIMIT 35",       
                      formBeanC.class, cF.getComments() );            
    }
    
    
    // parameter                   
    String jsonComments = new JSONSerializer()
                            .exclude("class")
                            .serialize( cF.getComments() );
    
    jsonComments = "({\"comments\":" + jsonComments + "})";
        
    response.getWriter().write( jsonComments );
    response.getWriter().flush();
    
    return null;
  }
}
